<?php

/*
Description: A PHP class to import Sina blogs into Wordpress-based Lyceum blog system.
Author: Xuefeng LIU, xfliu.math@gmail.com 
		Graduate School of Mathematical Sciences, The University of Tokyo,
		153-8914, Japan	

How to use it:

Put it into <lyceum folder>lib/wp-admin/import/, then it works!

Copyright: This code is free of charge. Anyone can change it and distribute it again with 
leaving this copyright info inside.

The author does not take any responsibility for the running results of this code.


Date: 2007/07/28

*/

error_reporting(E_ERROR | E_PARSE);

class SinaBlog_Import {

	var $posts = array ();
	var $uid;
	var $file;
	var $rss_data_index;
	var $rss_data_value;
	
// parse_leve, GetItem, ReadRss are used to read an xml file and parse it.
	function ParseEachLevel($name,$start,$level){
		
		$obj="";
		$i=$start;
		$j=0;

		while(! ($this->rss_data_value[$i]['type']=="close" and $this->rss_data_value[$i]['tag'] == $name )){

			if($this->rss_data_value[$i]['type']=="complete" and $this->rss_data_value[$i]['tag'] == $name ){
				$obj[$this->rss_data_value[$i]['tag']]=$this->rss_data_value[$i]['value'];
				$i++;	
				next;
			}
			if($this->rss_data_value[$i]['type']=="open"){
				$i++;
				$obj[$this->rss_data_value[$i-1]['tag']]=$this->ParseEachLevel($this->rss_data_value[$i-1]['tag'],&$i,$level+1);
				next;
			}
			$i++;
			$j++;
			if($j>100) break;
		}
		$start=$i+1;
		return $obj;
	}


	function GetItem($keyword,$ind=-1){

		$item_list=$this->rss_data_index[$keyword];
		$num=count($item_list );
		if($ind==-1){
			$j=0;
			while($j<$num){
				$obj[]=$this->ParseEachLevel($keyword,$item_list[$j],0);
				$j++;
			}
		}
		else{
			$item_start=$item_list[$ind];
			$obj=$this->ParseEachLevel($keyword,$item_start,0);
		}
		return $obj;
	}

	function ReadRss($URL,$id=0)
	{
		$aurl=fopen($URL,"r");
		if(!$aurl) return NULL;
		while(!feof($aurl)){
			$xml.=fgets($aurl,4096);
		}
		fclose($aurl);

		$parser = xml_parser_create();
		xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING,0);
		xml_parse_into_struct($parser,$xml,$this->rss_data_value,$this->rss_data_index);
		xml_parser_free($parser);
		}

	function get_file_body($URL){
	/* This funciton is used to parse an Sina blog article. You see, when the structure of 
	sina blog article changes, the function need to be updated.
	*/
		$aurl=fopen($URL,"r");
		$start=0;
		if(!$aurl) return NULL;
		while(!feof($aurl) ){
			$str=fgets($aurl,4096);
			if( preg_match('|service\.php|', $str) and $start==1 ){
				$start=0;
				break;
			}

			if ($start==1){
				$body.=$str;
			}
			if( preg_match('|A_font_change_sml|', $str) ){
				$str=preg_replace("/^(.*)sysBr500([^>]*)>/i", "", $str);
				$body.=$str;
				$start=1;
			}
		}
		fclose($aurl);
		return $body;
	}

	function header() {
		echo '<div class="wrap">';
		echo '<h2>'.__('Import Sina Blogs').'</h2>';
	}

	function footer() {
		echo '</div>';
	}

	function unhtmlentities($string) { // From php.net for < 4.3 compat
		return $string;
	}

	function greet() {
		echo '<p>'.__('Howdy! This importer allows you to import Sina blogs').'</p>';
		echo _('Please input the homepage url of your sina blog');
		echo '<br><br>
			<form  method="post" action="admin.php?import=sinablog&step=1">
	<div id="buttons">
	<label for="upload">';
		echo __("Homepage URL:"), '</label> <input id="upload" name="import_url" size=30 type="text" value="http://blog.sina.com.cn/???">
	<input name="action" value="save" type="hidden">
	<input value="Import It" type="submit">
	<input value="Cancel" onclick="cancelUpload()" type="button">
	</div>
	</form>	';
	}

	function get_posts($URL) {
		global $wpdb;
		
		set_magic_quotes_runtime(0);
		
		$uid=$_POST['import_uid'];
		

		foreach($_POST['import_cat'] as $cat){
			
			
			$page_over=0;
			$page=0;
			while(!$page_over){
				$page++;
				$URL="http://blog.sina.com.cn/sns/service.php?m=aList&uid=${uid}&sort_id=${cat}&page=${page}";
				$this->ReadRss($URL);
				$Titles=$this->GetItem("title");

				$Dates=$this->GetItem("sns:pubDate");
				$Links=$this->GetItem("link");
				$post_catalog = preg_replace("/^([^\-]+)-/","",$Titles[0]["title"]);
				$post_catalog = trim($post_catalog);
				
				echo __("Reading article in page").  $page." of ", $post_catalog  ," <br> \n ";
				echo "URL: ", $URL,"<br>\n";

		
				$i=0;
				$index=0;
				unset ($posts);
				foreach( $Links as $link){
					
					if($link["link"] and $link["link"] !="sns:index"  ){
	
						$mytitle=$Titles[$i+1];
						echo "Reading $i th article ...", $link["link"],"  " ,$mytitle["title"], " Date:",$Dates[$i]["sns:pubDate"], " ";
						
						if($post_id = post_exists($mytitle["title"], "" ,$Dates[$i]["sns:pubDate"])){
							echo " [Already imported!]";
							if (0 != count($categories) and $post_id)
								wp_create_categories(array($post_catalog), $post_id);
						}
						else{
							$url="http://blog.sina.com.cn".$link["link"];
							$content= $this->get_file_body($url);
							if(!$content){ echo "<br><b>Error!</b> $url ";$i++; $index++; continue;}
							$post["date"]=$Dates[$i]["sns:pubDate"];
							$post["title"]=$mytitle["title"];
							$post["content"]=$content;
							$post["category"]=array($post_catalog);
							
							/* ----------------------------------------------------
							// preparation for inserting into database.
							----------------------------------------------------  */							
							$post_title = $wpdb->escape(trim($post["title"]));
							if ($post["date"]) {
								$post_date = $post["date"];
							} else {
								$post_date = gmdate('Y-m-d H:i:s', $post_date);
							}

							$categories = $post["category"];

							$cat_index = 0;
							foreach ($categories as $category) {
								$categories[$cat_index] = $wpdb->escape($this->unhtmlentities($category));
								$cat_index++;
							}

							if ($guid)
								$guid = $wpdb->escape(trim($guid[1]));
							else
								$guid = '';

							$post_content = $post["content"];

							// Clean up content
							$post_content = preg_replace('|<(/?[A-Z]+)|e', "'<' . strtolower('$1')", $post_content);
							$post_content = str_replace('<br>', '<br />', $post_content);
							$post_content = str_replace('<hr>', '<hr />', $post_content);

							$post_author = 1;
							$post_status = 'publish';
							
							$this->posts[0] = compact('post_author', 'post_date', 'post_content', 'post_title', 'post_status', 'guid', 'categories');
							$this->import_posts();
/* ----------------------------------------------------
// preparation for inserting into database. OVER
----------------------------------------------------  */							
							
						}
						$i++;
						$index++;
					}
					echo "<br> \n ";
				}
				echo __("Articles in this page finished."), "<br> \n ";

				if(! $index ){ $page_over=1; break; }

			}

		}

	}

	function import_posts() {
		foreach ($this->posts as $post) {
			extract($post);
			
			if($post_title and $post_content and $post_date){

				if ($post_id = post_exists($post_title, $post_content, $post_date)) {
					_e('Post already imported');
				} else {
					$post_id = wp_insert_post($post);
					if (!$post_id) {
						_e("Couldn't get post ID");
						return;
					}

					if (0 != count($categories) )
						wp_create_categories($categories, $post_id);
				}
			}
		}
		_e('Done !');


	}
	function import() {
		$file = wp_import_handle_upload();
		echo $_POST['import_url'];
		$this->get_posts($_POST['import_url']);
		wp_import_cleanup($file['id']);
		
		echo '<h3>';
		printf(__('All done. <a href="%s">Have fun!</a>'), get_option('home'));
		echo '</h3>';
	}
	function cat_list(){
		
		$url=$_POST['import_url'];
		echo __("Your blog URL:"). $url."<br>\n";
		
		$fh=fopen($url,"r");
		if(!$fh) return NULL;
		while(!feof($fh)){
			$txt=fgets($fh,4096);
			if( preg_match('/<title>(.+)<\/title>/',$txt,$matched)){
				$blog_title=$matched[1];
			}
			if( preg_match('/UID([^\d]{1,5})([\d]{5,15})/',$txt,$matched)){
				$uid=$matched[2];
				break;
			}
		}
		fclose($fh);

		$this->uid=$uid;
		
		echo __("Your blog title:"). $blog_title."<br>\n";
		echo __("Your blog UID:") . $uid. "<br>\n";
		
		$sortid=0;		$no_re=0;

		echo '<form  method="post" action="admin.php?import=sinablog&step=2">';
		
		echo "<ul>";
		while(1){
		
			$URL="http://blog.sina.com.cn/sns/service.php?m=aList&uid=${uid}&sort_id=${sortid}";
			$this->ReadRss($URL);
			$Titles=$this->GetItem("title");
			if($Titles[0][title]){
				echo "<li>".$Titles[0][title]."<input type='checkbox' name=\"import_cat[]\" value=\"$sortid\">";
			}else{
				$no_re++;}
			$sortid++;	
			if($no_re>3) break;
		}
		
		echo "</ul>";
		echo "<input type='hidden' name='import_uid' value='$uid'>\n";
		echo '<div id="buttons"><input value="Import It" type="submit">
			  <input value="Cancel" onclick="cancelUpload()" type="button"></div></form>';
	
	}

	function dispatch() {
		if (empty ($_GET['step']))
			$step = 0;
		else
			$step = (int) $_GET['step'];

		$this->header();
		
		switch ($step) {
			case 0 :
				$this->greet();
				break;
			case 1 :
				$this->cat_list();
				break;
			case 2 :
				$this->import();
				break;
		}
		
		$this->footer();
	}

	function SinaBlog_Import() {
		// Nothing.	
	}
}

$sina_import = new SinaBlog_Import();

register_importer('sinablog', 'SINA', __('Import posts from a Sina Blog'), array ($sina_import, 'dispatch'));
?>
